import 'dart:async';
import 'dart:convert';
import 'dart:developer';

import 'package:dio/dio.dart' as dio;
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:handwrite/bean/responseData.dart';
import 'package:handwrite/request/exp.dart';

class NetworkService extends GetxService {
  static String originBaseUrl = "http://10.254.75.237:8080/";
  static final dio.Dio _dio = dio.Dio();

  static Future<ResponseData> post(
      {required String url,
      required Map<String, dynamic> map,
      loadingText = "加载中",
      bool showLoading = true,
      bool showErrToast = true,
      useFormData = false}) async {
    if (showLoading) {
      EasyLoading.show(status: loadingText);
    }
    try {
      var res = (await _dio.post("$originBaseUrl$url",
          options: dio.Options(contentType: 'multipart/form-data'),
          data: useFormData ? dio.FormData.fromMap(map) : map));
      if (showLoading) {
        EasyLoading.dismiss();
      }
      print("原始返回结构${res.data}");
      var data = ResponseData.fromJson(res.data);
      if (data.code == EXP.correct.code) {
        log("emmmmm($url)参数:${jsonEncode(map)}");
        log("emmmmm($url)结果:${jsonEncode(data.data)}");
        return data;
      }
      throw ApiException(code: data.code ?? "", message: data.message ?? "");
    } on ApiException catch (e) {
      if (showLoading) {
        EasyLoading.dismiss();
      }
      log("emmmmm($url)参数:${jsonEncode(map)}");
      log("emmmmm($url)接口报错:${e.toJson()}");
      rethrow;
    } on dio.DioException catch (e) {
      if (showLoading) {
        EasyLoading.dismiss();
      }
      rethrow;
    }
  }
}
